package com.palrevo.beackBeans.authentication;


import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import com.palrevo.beackBeans.BeansBase;
import com.palrevo.controllers.MsgsController;
import com.palrevo.controllers.NavigationController;
import com.palrevo.controllers.NavigationRule;
import com.palrevo.controllers.SystemMsgs;
import com.palrevo.data.dao.DataException;
import com.palrevo.data.models.User;
import com.palrevo.data.services.AuthenticationDBService;
import com.palrevo.utils.Log;
import com.palrevo.utils.StringUtils;
import com.palrevo.utils.WebUtils;

/**
 *
 * @author AAsha
 */
@ManagedBean(name="authenticationBean")
@RequestScoped
public class AuthenticationBean extends BeansBase {
	
	// Constants
	private static final long serialVersionUID = 1L;
	
	// Fields
	private String username;
	private String password;
	
	
	
	/**
	 * 
	 * @param USERNAME
	 * @param PASSWORD
	 */
	public void login(){
        
    	User user = null;
        
		try {
			user = AuthenticationDBService.getInstance().loadUser(username);
		} catch (DataException e) {
			e.printStackTrace();
			Log.error(this, e.getMessage());
			MsgsController.addErrorMessageKey(SystemMsgs.WRONGE_USER_OR_PASS);
			return;
		}
		
		if(user == null){
			MsgsController.addErrorMessageKey(SystemMsgs.WRONGE_USER_OR_PASS);
			return;
		}
		
        String userPassword = StringUtils.decryptString(user.getPassword(), user.hashCode());

        if(userPassword == null || !userPassword.equals(password)){
        	MsgsController.addErrorMessageKey(SystemMsgs.WRONGE_USER_OR_PASS);
        	return;
        }
        
        WebUtils.getAppSessionBean().setUser(user);
        
        NavigationController.navigate(NavigationRule.HOME);
    }
	
	/**
	 * 
	 */
	public void logout(){
		WebUtils.getRequest().getSession().invalidate();
		NavigationController.navigate(NavigationRule.LOGIN);
	}



	public String getUsername() {
		return username;
	}



	public void setUsername(String username) {
		this.username = username;
	}



	public String getPassword() {
		return password;
	}



	public void setPassword(String password) {
		this.password = password;
	}
	
	/*public static void main(String[] args) {
		User user = new User();
		user.setId(1L);
		
		String s = StringUtils.encryptString("P@ssw0rd", user.hashCode());
		System.out.println(s);
		
	}*/
    
}
